package com.zc.framework.shiro.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Created by zc on 2016/8/30.
 */
public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter  {
    public static final String DEFAULT_ERROR_CD_KEY_ATTRIBUTE_NAME = "shiroLoginFailure_Code";
    public static final String DEFAULT_CAPTCHA_PARAM = "validateCode";
    public static final String DEFAULT_DKEYACTION_PARAM = "dkeyAction";
    public static final String DEFAULT_DKEYTYPE_PARAM = "dkeyType";
    private String captchaParam = "validateCode";
    private String dkeyActionParam = "dkeyAction";
    private String dkeyTypeParam = "dkeyType";

    public FormAuthenticationFilter() {
    }

    public String getCaptchaParam() {
        return this.captchaParam;
    }

    public String getDkeyActionParam() {
        return this.dkeyActionParam;
    }

    protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, this.getCaptchaParam());
    }

    protected String getDkeyAction(ServletRequest request) {
        return WebUtils.getCleanParam(request, this.getDkeyActionParam());
    }

    protected String getDkeyType(ServletRequest request) {
        return WebUtils.getCleanParam(request, this.getDkeyTypeParam());
    }

    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = this.getUsername(request);
        String password = this.getPassword(request);
        if(password == null) {
            password = "";
        }

        boolean rememberMe = this.isRememberMe(request);
        String host = this.getHost(request);
        String captcha = this.getCaptcha(request);
        String dkeyAction = this.getDkeyAction(request);
        String dkeyType = this.getDkeyType(request);
        return new UsernamePasswordToken2(username, password.toCharArray(), rememberMe, host, captcha, dkeyAction, dkeyType);
    }

    protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
        String message = ae.getClass().getName();
        request.setAttribute(this.getFailureKeyAttribute(), message);
        request.setAttribute("shiroLoginFailure_Code", ae.getMessage());
    }

    public String getDkeyTypeParam() {
        return this.dkeyTypeParam;
    }

    public void setDkeyTypeParam(String dkeyTypeParam) {
        this.dkeyTypeParam = dkeyTypeParam;
    }
}
